/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package apresentacao.Carro;

import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.*;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import modelo_relacional.Carro;
import service.CarroService;


/**
 *
 * @author Rui Pereira
 */

public class CarroFrm extends javax.swing.JFrame {
    private Carro carro;
    private CarroService carroSevice;
    List<Carro> carros;
    /**
     * Creates new form CarroFrm
     */
    public CarroFrm() {
        initComponents();
        String timeStamp = new SimpleDateFormat("dd-MM-yyyy").format(Calendar.getInstance().getTime());
        this.dataCarroText.setText(timeStamp);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        criaCarroLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        matriculaLabel = new javax.swing.JLabel();
        chassiLabel = new javax.swing.JLabel();
        marcaLabel = new javax.swing.JLabel();
        anoLabel = new javax.swing.JLabel();
        cavalagemLabel = new javax.swing.JLabel();
        kmsLabel = new javax.swing.JLabel();
        activoLabel = new javax.swing.JLabel();
        matriculaTextF = new javax.swing.JTextField();
        chassiTextF = new javax.swing.JTextField();
        marcaTextF = new javax.swing.JTextField();
        anoTextF = new javax.swing.JTextField();
        cavalagemTextF = new javax.swing.JTextField();
        kmsTextF = new javax.swing.JTextField();
        activoTextF = new javax.swing.JTextField();
        gravarBtn = new javax.swing.JButton();
        novoBtn = new javax.swing.JButton();
        messageLabel = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        dataCarroLabel = new javax.swing.JLabel();
        dataCarroText = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Criar carro");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        criaCarroLabel.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        criaCarroLabel.setIcon(new javax.swing.ImageIcon("D:\\Java\\workspace\\GestaoObrasAutoSwing\\src\\apresentacao\\images\\carro.png")); // NOI18N
        criaCarroLabel.setText("Criar carro");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(criaCarroLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(criaCarroLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        matriculaLabel.setText("Matricula");

        chassiLabel.setText("Chassi");

        marcaLabel.setText("Marca");

        anoLabel.setText("Ano");

        cavalagemLabel.setText("Cavalagem");

        kmsLabel.setText("Kms");

        activoLabel.setText("Activo (S/N)");

        matriculaTextF.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                matriculaTextFFocusLost(evt);
            }
        });

        activoTextF.setText("S");

        gravarBtn.setText("Gravar");
        gravarBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gravarBtnActionPerformed(evt);
            }
        });

        novoBtn.setText("Novo");
        novoBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoBtnActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(153, 0, 0));
        jLabel1.setText("*");

        dataCarroLabel.setText("Data criação");

        dataCarroText.setEnabled(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cavalagemLabel)
                            .addComponent(marcaLabel)
                            .addComponent(activoLabel)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(matriculaLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(matriculaTextF)
                            .addComponent(marcaTextF)
                            .addComponent(cavalagemTextF)
                            .addComponent(activoTextF, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(dataCarroLabel)
                                .addGap(18, 18, 18)
                                .addComponent(dataCarroText))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(chassiLabel)
                                    .addComponent(anoLabel)
                                    .addComponent(kmsLabel))
                                .addGap(46, 46, 46)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(anoTextF, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(chassiTextF, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(kmsTextF, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(133, 133, 133)
                        .addComponent(gravarBtn)
                        .addGap(18, 18, 18)
                        .addComponent(novoBtn)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(messageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(matriculaLabel)
                    .addComponent(matriculaTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chassiLabel)
                    .addComponent(chassiTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(marcaLabel)
                    .addComponent(marcaTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(anoLabel)
                    .addComponent(anoTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cavalagemLabel)
                    .addComponent(cavalagemTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(kmsLabel)
                    .addComponent(kmsTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(dataCarroLabel)
                        .addComponent(dataCarroText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(activoLabel)
                        .addComponent(activoTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(25, 25, 25)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(gravarBtn)
                    .addComponent(novoBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(messageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 0, 102));
        jLabel2.setText("Software desenvolvido por SP. Todos os direitos reservados.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void getDadosFromText () {
        carro = new Carro();
        carro.setMatricula(this.getMatriculaTextF().getText());
        char conv = this.getActivoTextF().getText().charAt(0);
        carro.setActivo(conv);
        carro.setAno(this.getAnoTextF().getText());
        carro.setCavalagem(this.getCavalagemTextF().getText());
        carro.setChassi(this.getChassiTextF().getText());
        carro.setKms(this.getKmsTextF().getText());
        carro.setMarca(this.getMarcaTextF().getText());
    }

    public JTextField getDataCarroText() {
        return dataCarroText;
    }

    public void setDataCarroText(JTextField dataCarroText) {
        this.dataCarroText = dataCarroText;
    }
    
    private void limpaDadosFromText() {
        this.getMatriculaTextF().setText(null);
        this.getAnoTextF().setText(null);
        this.getCavalagemTextF().setText(null);
        this.getChassiTextF().setText(null);
        this.getKmsTextF().setText(null);
        this.getMarcaTextF().setText(null);
        this.getAnoTextF().setText(null);
    }

    public JLabel getAnoLabel() {
        return anoLabel;
    }

    public void setAnoLabel(JLabel anoLabel) {
        this.anoLabel = anoLabel;
    }
    
    private int checkCamposObrigatorios() {
        int check = 0; //0 = ok , 1 = NOK
        if (this.getMatriculaTextF().getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Os campos marcados com * são de preenchimento obrigatório.","Aviso",JOptionPane.WARNING_MESSAGE);
            check = 1;
        }
        return check;
    }
    
    private void novoBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoBtnActionPerformed
        limpaDadosFromText();
        this.matriculaTextF.requestFocus();
    }//GEN-LAST:event_novoBtnActionPerformed

    private void validaExisteMatricula() {
        carros = new ArrayList<Carro>();
        
        try {
        carroSevice = new CarroService();
        carros = carroSevice.viewCarro(this.matriculaTextF.getText());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Ocorreu um erro na validação da matricula.","Erro",JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void gravarBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gravarBtnActionPerformed
        // TODO add your handling code here:
        carroSevice = new CarroService();
        carros = new ArrayList<Carro>();
        getDadosFromText();
        try {
            if (checkCamposObrigatorios() == 0) {
                
                    carroSevice.criaAlteraCarro(carro, "Insert");  
                    this.messageLabel.setForeground(Color.BLUE);
                    this.messageLabel.setText("Carro criado com sucesso. Registo interno: "+String.valueOf(carro.getCarro_id()));
                    limpaDadosFromText();
            } 
        } catch (Exception e){
            JOptionPane.showMessageDialog(this, "Ocorreu um erro a criar o carro.","Erro",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_gravarBtnActionPerformed

    private void matriculaTextFFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_matriculaTextFFocusLost
        validaExisteMatricula();
        if (carros.size() == 1) {
            this.matriculaTextF.setFocusable(true);
            camposDisabled();
            JOptionPane.showMessageDialog(this, "A matricula inserida já existe.","Erro",JOptionPane.ERROR_MESSAGE);
            this.matriculaTextF.requestFocus();
        }
        else {
            camposEnabled();
            this.chassiTextF.requestFocus();
            return;
        }
    }//GEN-LAST:event_matriculaTextFFocusLost

    private void camposDisabled() {
        this.getAnoTextF().setEnabled(false);
        this.getCavalagemTextF().setEnabled(false);
        this.getChassiTextF().setEnabled(false);
        this.getKmsTextF().setEnabled(false);
        this.getMarcaTextF().setEnabled(false);
        this.getAnoTextF().setEnabled(false);
        this.getActivoTextF().setEnabled(false);
    }
    
    private void camposEnabled() {
        this.getAnoTextF().setEnabled(true);
        this.getCavalagemTextF().setEnabled(true);
        this.getChassiTextF().setEnabled(true);
        this.getKmsTextF().setEnabled(true);
        this.getMarcaTextF().setEnabled(true);
        this.getAnoTextF().setEnabled(true);
        this.getActivoTextF().setEnabled(true);
    }
   
    public JTextField getActivoTextF() {
        return activoTextF;
    }

    public void setActivoTextF(JTextField activoTextF) {
        this.activoTextF = activoTextF;
    }

    public JTextField getAnoTextF() {
        return anoTextF;
    }

    public void setAnoTextF(JTextField anoTextF) {
        this.anoTextF = anoTextF;
    }

    public JTextField getCavalagemTextF() {
        return cavalagemTextF;
    }

    public void setCavalagemTextF(JTextField cavalagemTextF) {
        this.cavalagemTextF = cavalagemTextF;
    }

    public JTextField getChassiTextF() {
        return chassiTextF;
    }

    public void setChassiTextF(JTextField chassiTextF) {
        this.chassiTextF = chassiTextF;
    }

    public JTextField getKmsTextF() {
        return kmsTextF;
    }

    public void setKmsTextF(JTextField kmsTextF) {
        this.kmsTextF = kmsTextF;
    }

    public JTextField getMarcaTextF() {
        return marcaTextF;
    }

    public void setMarcaTextF(JTextField marcaTextF) {
        this.marcaTextF = marcaTextF;
    }

    public JTextField getMatriculaTextF() {
        return matriculaTextF;
    }

    public void setMatriculaTextF(JTextField matriculaTextF) {
        this.matriculaTextF = matriculaTextF;
    }

    public JLabel getMessageLabel() {
        return messageLabel;
    }

    public void setMessageLabel(JLabel messageLabel) {
        this.messageLabel = messageLabel;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CarroFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CarroFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CarroFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CarroFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CarroFrm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel activoLabel;
    private javax.swing.JTextField activoTextF;
    private javax.swing.JLabel anoLabel;
    private javax.swing.JTextField anoTextF;
    private javax.swing.JLabel cavalagemLabel;
    private javax.swing.JTextField cavalagemTextF;
    private javax.swing.JLabel chassiLabel;
    private javax.swing.JTextField chassiTextF;
    private javax.swing.JLabel criaCarroLabel;
    private javax.swing.JLabel dataCarroLabel;
    private javax.swing.JTextField dataCarroText;
    private javax.swing.JButton gravarBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel kmsLabel;
    private javax.swing.JTextField kmsTextF;
    private javax.swing.JLabel marcaLabel;
    private javax.swing.JTextField marcaTextF;
    private javax.swing.JLabel matriculaLabel;
    private javax.swing.JTextField matriculaTextF;
    private javax.swing.JLabel messageLabel;
    private javax.swing.JButton novoBtn;
    // End of variables declaration//GEN-END:variables

    
}
